package com.bykj.property.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bykj.property.service.PmVillageService;
import com.bykj.property.model.PmVillage;
import com.bykj.property.config.common.exception.CustomException;
import com.bykj.property.controller.vo.response.ErrorCode;
import com.bykj.property.controller.vo.response.RespResult;
import com.bykj.property.controller.vo.request.PmVillagePageRequest;
import com.bykj.property.controller.vo.export.PmVillageExport;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.bykj.property.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import javax.servlet.http.HttpServletRequest;
import org.springframework.validation.BindingResult;

import javax.validation.ValidationException;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.alibaba.fastjson.JSON;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import javax.validation.constraints.NotEmpty;

    import org.springframework.web.bind.annotation.RestController;

/**
* <p>
    * 小区信息表 前端控制器
    * </p>
*
* @author liangyiming
* @since 2019-06-20
*/

@Slf4j
    @Api(tags = {"小区信息表"})
    @RestController
   @RequestMapping("/admin/PmVillage")
        public class PmVillageController {
    @Autowired
    PmVillageService targetService;

    @ApiOperation(value="添加")
    @RequestMapping(value = "/add",method = RequestMethod.POST,produces = "application/json;charset=UTF-8" )
    public RespResult add(PmVillage model, BindingResult bindingResult) {
    return RespResult.ok(targetService.save(model));
    }

    @ApiOperation(value="更新")
    @RequestMapping(value = "/update",method = RequestMethod.POST,produces = "application/json;charset=UTF-8" )
    public RespResult update(PmVillage model) {
    return RespResult.ok(targetService.updateById(model));
    }

    @ApiOperation(value="删除接口")
    @RequestMapping(value = "/delete",method = RequestMethod.POST,produces = "application/json;charset=UTF-8" )
    public RespResult delete(@NotEmpty String id) {
    return RespResult.ok(targetService.removeById(id));
    }

    @ApiOperation(value="查询列表接口")
    @RequestMapping(value = "/query",method = RequestMethod.POST,produces = "application/json;charset=UTF-8" )
    public RespResult query(PmVillagePageRequest pageRequest, BindingResult bindingResult) {
    if(pageRequest.getSize()==-1){
    return RespResult.ok(targetService.list());
    }
    return RespResult.ok(targetService.queryPage(pageRequest));
    }

    @ApiOperation(value="查询详情接口")
    @ApiImplicitParams({
    @ApiImplicitParam(name="id",value="id",dataType="String", paramType = "query")
    })
    @RequestMapping(value = "/get",method = RequestMethod.POST,produces = "application/json;charset=UTF-8" )
    public RespResult get(@NotEmpty String id) {
    return RespResult.ok(targetService.getById(id));
    }
    // 导出操作
    @ApiOperation(value="导出excel表格")
    @RequestMapping("/exportExcel")
    public void export(PmVillagePageRequest pageRequest,HttpServletResponse response) {
        List<PmVillage> list =null;
        QueryWrapper queryWrapper=new QueryWrapper();
        if(!StringUtils.isEmpty(pageRequest.getViName())){
            queryWrapper.like("vi_name",pageRequest.getViName());
        }
        if(!StringUtils.isEmpty(pageRequest.getViNumber())){
            queryWrapper.like("vi_number",pageRequest.getViNumber());
        }


        if(pageRequest.getSize()==-1){
            list=targetService.list(queryWrapper);
        }else{
            list=targetService.page(pageRequest,queryWrapper).getRecords();
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        // 模拟从数据库获取需要导出的数据
        List<PmVillageExport> listExport = JSON.parseArray(JSON.toJSONString(list),PmVillageExport.class);
        // 导出操作
        ExcelUtils.exportExcel(listExport, "小区信息表", "PmVillage", PmVillageExport.class, "PmVillage-"+formatter.format(new Date())+".xls", response);

    }
    @ApiOperation(value="导入excel表格")
    @PostMapping("/importExcel")
    public RespResult importExcel2(@RequestParam("file") MultipartFile file) {
        ImportParams importParams = new ImportParams();
        // 数据处理
        importParams.setHeadRows(1);
        importParams.setTitleRows(1);
        // 需要验证
        importParams.setNeedVerfiy(false);

        try {
            ExcelImportResult<PmVillageExport> result = ExcelImportUtil.importExcelMore(file.getInputStream(), PmVillageExport.class,
                    importParams);
            List<PmVillageExport> list = result.getList();
            List<PmVillage> pmVillageList=JSON.parseArray(JSON.toJSONString(list),PmVillage.class);
            targetService.saveOrUpdateBatch(pmVillageList);
            log.info("从Excel导入数据一共 {} 行 ", list.size());
        } catch (IOException e) {

            log.error("导入失败：{}", e.getMessage());
            return RespResult.error(ErrorCode.SYS_ERR);
        } catch (Exception e1) {

            log.error("导入失败：{}", e1.getMessage());
            return RespResult.error(ErrorCode.SYS_ERR);
        }
        return RespResult.ok();
    }


}
